package com.itmei.sms.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itmei.sms.config.SmsSupplierConfig;
import com.itmei.sms.entity.SmsConfig;
import com.itmei.sms.entity.SmsResult;
import com.itmei.sms.entity.SmsTemplateConfig;
import com.itmei.sms.entity.SysSms;
import com.itmei.sms.enums.SmsResponseEnum;
import com.itmei.sms.enums.SmsSendSourceEnum;
import com.itmei.sms.enums.SmsSendStatusEnum;
import com.itmei.sms.exception.ServiceException;
import com.itmei.sms.service.SmsInterface;
import com.itmei.sms.service.SmsServiec;
import com.itmei.sms.service.SysSmsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author itmei
 * @Date 2023/1/31 14:21
 * @description:
 * @Title: SmsServiecImpl
 * @Package com.itmei.sms.service.impl
 */
@Service
public class SmsServiecImpl implements SmsServiec {


    @Resource
    private SysSmsService sysSmsService;
    /**
     * 阿里云
     */
    SmsInterface aliyunService = new SmsAliyunServiceImpl();
    /**
     * 腾讯云
     */
    SmsInterface tencentService = new SmsTencentServiceImpl();

    @Override
    public void sendSms(String mobile, SmsTemplateConfig smsTemplateConfig,boolean verifyPhon) {
        if (!SmsSupplierConfig.smsSendOrNot){
            doNotSendSave(mobile,smsTemplateConfig);
            return;
        }

        //获取发送短信的服务商
        SmsInterface smsInterface = smsSupplier(smsTemplateConfig.getSupplierEnum());
        if (ObjectUtil.isNull(smsInterface)){
            //获取不到对应服务商
            throw new ServiceException(102,"获取不到对应服务商");
        }
        if (verifyPhon){
            boolean verify = verifySendingMobile(smsTemplateConfig.getSceneEnum(), mobile);
            if (verify){
                throw new ServiceException(105,"短信已发送，稍后在试！");
            }
        }

        //短信服务商-配置信息
        JSONObject supplier = SmsSupplierConfig.smsConfig.getJSONObject(smsTemplateConfig.getSupplierEnum());
        SmsConfig smsConfig = new SmsConfig();
        smsConfig.setAccessKeyId(supplier.getStr("accessKeyId"));
        smsConfig.setAccessKeySecret(supplier.getStr("accessKeySecret"));
        smsConfig.setSignName(supplier.getStr("signName"));

        SmsResult result = smsInterface.sendSms(smsConfig,mobile, smsTemplateConfig);
        if (!SmsResponseEnum.OK.getCode().equals(result.getCode())){
            //发送失败
            throw new ServiceException(104,"短信, "+result.getErrorMsg());
        }

        //保存手机号短信信息
        SysSms sysSms = result.getSysSms();
        //设置使用的短信供应商
        sysSms.setSmsSupplier(smsTemplateConfig.getSupplierEnum());
        //场景
        sysSms.setScene(smsTemplateConfig.getSceneEnum());
        //发送状态
        sysSms.setStatus(SmsSendStatusEnum.SUCCESS.getCode());
        //来源
        sysSms.setSource(smsTemplateConfig.getSourceEnum());
        //过期时间5分钟
        sysSms.setInvalidTime(DateUtil.offsetMinute(new Date(),5));
        sysSmsService.save(sysSms);
    }

    @Override
    public void asynchronousSendSms(String mobile, SmsTemplateConfig smsTemplateConfig) {
        if (!SmsSupplierConfig.smsSendOrNot){
            doNotSendSave(mobile,smsTemplateConfig);
            return;
        }

        StringBuffer errorMsg = new StringBuffer();

        //获取发送短信的服务商
        SmsInterface smsInterface = smsSupplier(smsTemplateConfig.getSupplierEnum());
        if (ObjectUtil.isNull(smsInterface)){
            //获取不到对应服务商
            errorMsg.append("获取不到对应服务商,");
        }
        //短信服务商-配置信息
        JSONObject supplier = SmsSupplierConfig.smsConfig.getJSONObject(smsTemplateConfig.getSupplierEnum());
        SmsConfig smsConfig = new SmsConfig();
        smsConfig.setAccessKeyId(supplier.getStr("accessKeyId"));
        smsConfig.setAccessKeySecret(supplier.getStr("accessKeySecret"));
        smsConfig.setSignName(supplier.getStr("signName"));

        if (errorMsg.length()>0){
            saveSmsError(smsTemplateConfig,mobile,errorMsg.toString());
            return;
        }
        SmsResult result = smsInterface.sendSms(smsConfig,mobile, smsTemplateConfig);
        if (!SmsResponseEnum.OK.getCode().equals(result.getCode())){
            //发送失败
            saveSmsError(smsTemplateConfig,mobile,result.getErrorMsg());
            return;
        }
        //保存手机号短信信息
        SysSms sysSms = result.getSysSms();
        //设置使用的短信供应商
        sysSms.setSmsSupplier(smsTemplateConfig.getSupplierEnum());
        //场景
        sysSms.setScene(smsTemplateConfig.getSceneEnum());
        //发送状态
        sysSms.setStatus(SmsSendStatusEnum.SUCCESS.getCode());
        //来源
        sysSms.setSource(smsTemplateConfig.getSourceEnum());
        //过期时间5分钟
        sysSms.setInvalidTime(DateUtil.offsetMinute(new Date(),5));
        sysSmsService.save(sysSms);
    }

    public void saveSmsError(SmsTemplateConfig smsTemplateConfig,String mobile,String errorMsg){
        SysSms sysSms = new SysSms();
        sysSms.setPhoneNumbers(mobile);
        sysSms.setTemplateParam(JSONUtil.toJsonStr(smsTemplateConfig.getTemplateParam()));
        //设置使用的短信供应商
        sysSms.setSmsSupplier(smsTemplateConfig.getSupplierEnum());
        //场景
        sysSms.setScene(smsTemplateConfig.getSceneEnum());
        //发送状态
        sysSms.setStatus(SmsSendStatusEnum.FAILED.getCode());
        //来源
        sysSms.setSource(smsTemplateConfig.getSourceEnum());
        sysSms.setErrorMsg(errorMsg);
        sysSmsService.save(sysSms);
    }

    /**
     * 不开启短信发送保存模板
     * @param mobile
     * @param smsTemplateConfig
     */
    public void doNotSendSave(String mobile, SmsTemplateConfig smsTemplateConfig){
        SysSms sysSms = new SysSms();
        sysSms.setPhoneNumbers(mobile);
        sysSms.setValidateCode(RandomUtil.randomNumbers(6));
        //设置使用的短信供应商
        sysSms.setSmsSupplier(smsTemplateConfig.getSupplierEnum());
        //场景
        sysSms.setScene(smsTemplateConfig.getSceneEnum());
        //发送状态
        sysSms.setStatus(SmsSendStatusEnum.SUCCESS.getCode());
        //来源其他
        sysSms.setSource(SmsSendSourceEnum.OTHER.getCode());
        //过期时间5分钟
        sysSms.setInvalidTime(DateUtil.offsetMinute(new Date(),5));
        sysSmsService.save(sysSms);
    }

    /**
     * 通过枚举返回对应短信服务商
     *
     * @param supplierEnumCode
     * @return
     */
    public SmsInterface smsSupplier(String supplierEnumCode) {
        if (SmsAliyunServiceImpl.Code.equals(supplierEnumCode)) {
            return aliyunService;
        } else if (SmsTencentServiceImpl.Code.equals(supplierEnumCode)) {
            return tencentService;
        }
        return null;
    }

    /**
     * 验证发送手机号
     *
     * @param scene  场景
     * @param mobile 手机号
     * @return
     */
    public boolean verifySendingMobile(Integer scene, String mobile) {
        LambdaQueryWrapper<SysSms> sysSmsQ = new LambdaQueryWrapper<>();
        sysSmsQ.eq(SysSms::getPhoneNumbers, mobile)
                .eq(SysSms::getScene, scene)
                .gt(SysSms::getInvalidTime, DateUtil.now());
        SysSms sms = sysSmsService.getOne(sysSmsQ);
        if (ObjectUtil.isNotEmpty(sms)) {
            return true;
        }
        return false;
    }
}
